package com.wenhuitec.android.tang.ui.activity;

import static java.lang.Thread.sleep;

import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dhkj.web.utils.MyObserverRes;
import com.dhkj.web.utils.RequestUtils;
import com.wenhuitec.android.tang.R;
import com.wenhuitec.android.tang.config.SystemInit;
import com.wenhuitec.android.tang.entity.DeviceCarModel;
import com.wenhuitec.android.tang.sysui.model.CarFoodsModel;
import com.wenhuitec.android.tang.ui.dialog.MsgDialog;
import com.wenhuitec.android.tang.util.BytesUtil;
import com.wenhuitec.android.tang.util.PrintUtil;
import com.wenhuitec.android.tang.util.ScanKeyManager;
import com.wenhuitec.android.tang.util.UsbPrinter;
import com.yzy.voice.VoicePlay;

import org.w3c.dom.Text;

import java.util.List;
import java.util.Map;

public class ScanQrActivity extends AppCompatActivity {

    private Context mContext;
    private ScanKeyManager scanKeyManager;
    private String orders = "";
    private UsbPrinter usbPrinter;
    private Button cancelBut;
    private Button checkBut;
    private TextView priceTv;
    private TextView msgTv;
    private String price = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_qr);
        mContext = this;
        String data = this.getIntent().getExtras().getString("data");
        usbPrinter = UsbPrinter.getInstance(this);
        cancelBut = findViewById(R.id.cancel_button);
        priceTv = findViewById(R.id.priceTv);
        msgTv = findViewById(R.id.msgTv);

//        DeviceCarModel carFoodsModelList = JSONObject.parseObject(data, DeviceCarModel.class);
//        if (carFoodsModelList == null || carFoodsModelList.getCarFoods().size() == 0) {
//            finish();
//            return;
//        }

        List<DeviceCarModel> deviceCarModelList = JSONArray.parseArray(data, DeviceCarModel.class);
        if (deviceCarModelList == null ||
                deviceCarModelList.size() == 0 ||
                deviceCarModelList.get(0).getCarFoods().size() == 0) {
            finish();
            return;
        }

        RequestUtils.toPrePay(mContext, new MyObserverRes<Map<String, String>>(mContext) {
            @Override
            public void onSuccess(Map<String, String> result) {
                System.out.println(result.toString());
                orders = result.get("orders");
                price = result.get("amountPrice");
                priceTv.setText("￥" + result.get("amountPrice"));
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                System.out.println(errorMsg);
            }
        }, data);

        VoicePlay.with(mContext).showQR();  //播报请出示二维码
        cancelBut.setOnClickListener(v -> {
            finish();
        });

        checkBut = findViewById(R.id.check_button);
        checkBut.setOnClickListener(view -> {
            showInputPassword();
        });

        scanKeyManager = new ScanKeyManager((String value) -> {
//            Log.i("MainActivity", "ScanValue->" + value);
            if (price == null || "".equals(price)) {

                return;
            }
            cancelBut.setEnabled(false);
            RequestUtils.microPay(mContext, orders, value, new MyObserverRes<String>(mContext) {
                @Override
                public void onSuccess(String result) {
                    if (result == null) {
                        return;
                    }
//                    DeviceCarModel deviceCarModel = JSONObject.parseObject(result, DeviceCarModel.class);
                    List<DeviceCarModel> deviceCarModels = JSONArray.parseArray(result, DeviceCarModel.class);
                    if (deviceCarModels == null ||
                            deviceCarModels.size() == 0 ||
                            deviceCarModels.get(0).getResultCode() <= 0) {
                        //进入查单
                        showInputPassword();
                        return;
                    }
//                    MsgDialog msgDialog = new MsgDialog();
//                    msgDialog.show(mContext, "                      是否打印                      ", new MsgDialog.OnBottomClickListener() {
//                        @Override
//                        public void positive() {
//                            byte[] printByte = BytesUtil.printOrder(deviceCarModel);
//                            if (printByte != null) {
//                                usbPrinter.write(printByte);
//                            }
//                            finish();
//                        }
//
//                        @Override
//                        public void negative() {
//                            finish();
//                        }
//                    });

                    try {
                        for (DeviceCarModel goo : deviceCarModels) {
                            PrintUtil.setPrintDevice(SystemInit.getInstance(mContext).getPrintDeviceType());
                            byte[] printByte = BytesUtil.printOrder(goo);
                            if (printByte != null) {
                                usbPrinter.write(printByte);
                            }
                        }
//                        byte[] printByte = BytesUtil.printOrder(deviceCarModel);
//                        if (printByte != null) {
//                            usbPrinter.write(printByte);
//                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

//                    byte[] printByte = BytesUtil.printOrder(deviceCarModel);
//                    if (printByte != null) {
//                        usbPrinter.write(printByte);
//                    }
                    finish();
                }

                @Override
                public void onFailure(Throwable e, String errorMsg) {
                    cancelBut.setEnabled(true);
                    checkBut.setVisibility(View.VISIBLE);
                    msgTv.setText(errorMsg);
                }
            });
        });
    }

    //需要输入密码
    private void showInputPassword() {
        //播报语音
        msgTv.setText("正在查单，请检查是否要输入密码");
        //查询订单状态，直到成功或者失败
        RequestUtils.checkOrder(mContext, orders, new MyObserverRes<String>(mContext, false) {
            @Override
            public void onSuccess(String result) {
//                DeviceCarModel deviceCarModel = JSONObject.parseObject(result, DeviceCarModel.class);
//                if (deviceCarModel.getResultCode() == 0) {
//                    //进入查单
//                    try {
//                        sleep(2000);
//                        showInputPassword();
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    return;
//                }

                List<DeviceCarModel> deviceCarModels = JSONArray.parseArray(result, DeviceCarModel.class);
                if (deviceCarModels == null ||
                        deviceCarModels.size() == 0 ||
                        deviceCarModels.get(0).getResultCode() == 0) {

                    //                    //进入查单
                    try {
                        sleep(2000);
                        showInputPassword();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return;

                }

//                if (deviceCarModel.getResultCode() < 0) {
//                    cancelBut.setEnabled(true);
//                    msgTv.setText("支付未成功，请返回重新下单");
//                    return;
//                }

                if (deviceCarModels.get(0).getResultCode() < 0) {

                    cancelBut.setEnabled(true);
                    msgTv.setText("支付未成功，请返回重新下单");
                    return;

                }
                msgTv.setText("支付成功");
//                MsgDialog msgDialog = new MsgDialog();
//                msgDialog.show(mContext, "                      是否打印                      ", new MsgDialog.OnBottomClickListener() {
//                    @Override
//                    public void positive() {
//                        byte[] printByte = BytesUtil.printOrder(deviceCarModel);
//                        try {
//                            if (printByte != null) {
//                                usbPrinter.write(printByte);
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                        finish();
//                    }
//
//                    @Override
//                    public void negative() {
//                        finish();
//                    }
//                });


                try {
                    for (DeviceCarModel goo : deviceCarModels) {
                        PrintUtil.setPrintDevice(SystemInit.getInstance(mContext).getPrintDeviceType());
                        byte[] printByte = BytesUtil.printOrder(goo);
                        if (printByte != null) {
                            usbPrinter.write(printByte);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                finish();
            }

            @Override
            public void onFailure(Throwable e, String errorMsg) {
                cancelBut.setEnabled(true);
                msgTv.setText(errorMsg);
            }
        });

    }


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() != KeyEvent.KEYCODE_BACK) {
            scanKeyManager.analysisKeyEvent(event);
            return true;
        }
        return super.dispatchKeyEvent(event);
    }
}